package com.demo.facerecognition;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.demo.facerecognition.view.FaceView;

import java.io.File;
import java.io.IOException;

/**
 * 人脸识别预览视频由相机预览显示
 * 这个可以根据SDK决定
 * <p>
 * 预览界面
 */
public class PreviewActivity extends AppCompatActivity {
    private final String TAG = "PreviewActivity";
    private Camera mCamera;
    private boolean isPreview = false;
    final String[] PERMISSION = new String[]{
            //获取照相机权限
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private FaceView faceView;
    private MediaRecorder mediaRecorder;
    //计时器
    private Handler mHandle = new Handler();
    //当前微秒数
    private long currentSecond = 0;
    private long countUp = 0;

    /**
     * 设置Android6.0的权限申请
     */
    private void setPermissions() {
        if (ContextCompat.checkSelfPermission(PreviewActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //Android 6.0申请权限
            ActivityCompat.requestPermissions(this, PERMISSION, 1);
        } else {
            Log.i(TAG, "权限申请ok");
        }
    }

    Button btnStop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        mediaRecorder = new MediaRecorder();
        //初始化布局
        ConstraintLayout constraintLayout = findViewById(R.id.cl_root);
        faceView = findViewById(R.id.fv_title);
        Button changeBtn = findViewById(R.id.changge);
        Button btnStart = findViewById(R.id.btnStart);
        btnStop = findViewById(R.id.btnStop);

        //申请手机的权限
        setPermissions();

        changeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = (int) (1 + Math.random() * 4);
                switch (i) {
                    case 1:
                        faceView.resetPositionStart();
                        faceView.updateTipsInfo("没有检测人脸");
                        break;
                    case 2:
                        faceView.backAnimator();
                        faceView.updateTipsInfo("请露正脸");
                        break;
                    case 3:
                        faceView.pauseAnimator();
                        faceView.updateTipsInfo(" 眨眨眼");
                        break;
                    case 4:
                        faceView.startAnimator();
                        faceView.updateTipsInfo("离近一点");
                        break;
                    default:
                        break;
                }
            }
        });

        //添加布局
        SurfaceView mSurfaceView = new SurfaceView(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mSurfaceView.setLayoutParams(params);
        constraintLayout.addView(mSurfaceView, 0);
        //得到getHolder实例
        SurfaceHolder mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);
        // 添加 Surface 的 callback 接口
        mSurfaceHolder.addCallback(mSurfaceCallback);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!prepareMediaRecorder()) {
                    Toast.makeText(PreviewActivity.this, "初始化摄像头失败！", Toast.LENGTH_SHORT).show();
                }
                //开始录制视频
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            isPause = false;
                            mediaRecorder.start();
                            mHandle.postDelayed(timeRunnable, 100);
                        } catch (final Exception ex) {
                            releaseMediaRecorder();
                        }
                    }
                });

            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //停止录制
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                //暂停录制
                                mediaRecorder.pause();
                            } else {
                                mediaRecorder.stop();
                            }
                        } catch (final Exception ex) {
                            releaseMediaRecorder();
                        }
                    }
                });
            }
        });
    }

    private int quality = CamcorderProfile.QUALITY_720P;
    private String CAMERA_FILE_PATH = "com.demo.facerecognition";
    private String url_file = Environment.getExternalStorageDirectory().getPath() + "/" + CAMERA_FILE_PATH + "/in.mp4";
    //是否暂停
    private boolean isPause = false;
    /**
     * 计时器
     */
    private Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            currentSecond = currentSecond + 100;
            countUp = currentSecond / 100;
            String h = "", t = "";
            if (countUp / 100 % 10 > 0) {
                h = countUp / 100 % 10 + "";
            }
            if (countUp / 10 % 10 >= 0) {
                t = countUp / 10 % 10 + ".";
            }
            String asText = h + t + countUp % 10 + "秒";
            btnStop.setText("停止(" + asText + ")");
            if (countUp == 50) {
                countUp = 0;
                currentSecond = 0;
                //停止录制
                mediaRecorder.stop();
                isPause = true;
                //停止计时
                mHandle.removeCallbacks(timeRunnable);
                btnStop.setText("停止");
            }
            if (!isPause) {
                mHandle.postDelayed(this, 100);
            }
        }
    };

    /**
     * 初始化录制视频
     *
     * @return
     */
    private boolean prepareMediaRecorder() {
        if (mCamera != null) {
            mCamera.unlock();
            mediaRecorder.setCamera(mCamera);
        }
//        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mediaRecorder.setOrientationHint(270);
        mediaRecorder.setProfile(CamcorderProfile.get(quality));
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + CAMERA_FILE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file1 = new File(url_file);
        if (file1.exists()) {
            file1.delete();
        }
        mediaRecorder.setOutputFile(url_file);
        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            releaseMediaRecorder();
            return false;
        }
        return true;
    }

    /**
     * 拍视频
     * end
     */
    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.reset();
            mediaRecorder.release();
            mediaRecorder = null;
            if (mCamera != null) {
                mCamera.lock();
            }
        }
    }

    private SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                //打开硬件摄像头，这里导包得时候一定要注意是android.hardware.Camera
                // Camera,open() 默认返回的后置摄像头信息
                //设置角度，此处 CameraId 我默认 为 1 （前置）
                if (Camera.getNumberOfCameras() > 1) {
                    mCamera = Camera.open(1);
                } else {
                    mCamera = Camera.open(0);
                }
                //设置相机角度
                mCamera.setDisplayOrientation(90);
                //通过SurfaceView显示取景画面
                mCamera.setPreviewDisplay(surfaceHolder);
                //开始预览
                mCamera.startPreview();
                //设置是否预览参数为真
                isPreview = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (mCamera != null) {
                if (isPreview) {//正在预览
                    try {
                        mCamera.stopPreview();
                        mCamera.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        //释放资源
        faceView.destroyView();
        if (mCamera != null) {
            //正在预览
            if (isPreview) {
                try {
                    mCamera.release();
                    mCamera = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        super.onDestroy();
    }
}